<?php namespace App\Services;

use Illuminate\Http\Request;
use Auth;
use Exception;
use App\Models\Item;
use App\Models\Match;

class MatchService
{

    public function getList(Request $request)
    {
        $search = Match::where([]);
        $confirm = $request->input('confirm');
        if ($confirm == 'confirm') {
            $search->where('confirm', 1);
        } elseif ($confirm == 'un_confirm') {
            $search->where('confirm', 0);
        }
        return $search->orderBy($request->input('orderField', 'id'), $request->input('orderDirection', 'asc'))
            ->paginate($request->input('pageSize', config('view')['numPerPage']));
    }

    public function create($id, $match_id)
    {
        if (($item = Item::find($id)) && ($matchItem = Item::find($match_id))) {
            if ($item->type == $matchItem->type) {
                throw new Exception('相同类型不能匹配');
            }
            if (Match::where('lost_item_id', $id)
                    ->orWhere('lost_item_id', $match_id)
                    ->orWhere('find_item_id', $id)
                    ->orWhere('find_item_id', $match_id)->count() > 0
            ) {
                throw new Exception($matchItem->name . '已被认领');
            }
            return Match::create([
                'find_item_id' => $item->type == 'find' ? $id : $match_id,
                'lost_item_id' => $item->type == 'find' ? $match_id : $id,
                'match_user_id' => Auth::user()->id
            ]);
        }
        throw new Exception('物品不存在');
    }

    public function confirm($id)
    {
        $match = Match::find($id);
        if ($match->confirm) {
            throw new Exception('匹配已被确认');
        }
        $match->confirm = true;
        $match->confirm_user_id = Auth::user()->id;
        return $match->save();
    }

    public function unConfirm($id)
    {
        $match = Match::find($id);
        if (!$match->confirm) {
            throw new Exception('匹配还未被确认');
        }
        $match->confirm = false;
        $match->confirm_user_id = null;
        return $match->save();
    }


    public function delete($id)
    {
        $match = Match::find($id);
        if ($match->confirm) {
            throw new Exception('匹配已被确认，不能删除');
        }
        return $match->delete();
    }
}